package com.foodcommunity.controller;

import com.foodcommunity.common.Result;
import com.foodcommunity.config.AMapConfig;
import com.foodcommunity.entity.Restaurant;
import com.foodcommunity.service.RestaurantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 美食地图控制器
 */
@RestController
@RequestMapping("/api/food-map")
public class FoodMapController {

    @Autowired
    private RestaurantService restaurantService;

    @Autowired
    private AMapConfig amapConfig;

    @Autowired
    private RestTemplate restTemplate;

    private static final String AMAP_REST_BASE_URL = "https://restapi.amap.com/v3";

    /**
     * 获取地图上的餐厅标记
     */
    @GetMapping("/markers")
    public Result<List<Map<String, Object>>> getRestaurantMarkers(
            @RequestParam(required = false) String cuisineType,
            @RequestParam(required = false) Integer minPrice,
            @RequestParam(required = false) Integer maxPrice,
            @RequestParam(required = false) Double minRating) {
        
        // 获取餐厅列表
        Map<String, Object> result = restaurantService.getRestaurantsByCondition(
                cuisineType, minPrice, maxPrice, minRating, 1, 100);
        
        @SuppressWarnings("unchecked")
        List<Restaurant> restaurants = (List<Restaurant>) result.get("restaurants");
        
        // 转换为地图标记格式
        List<Map<String, Object>> markers = convertToMarkers(restaurants);
        
        return Result.success(markers);
    }
    
    /**
     * 获取指定区域内的餐厅
     */
    @GetMapping("/area")
    public Result<List<Map<String, Object>>> getRestaurantsInArea(
            @RequestParam Double northLat,
            @RequestParam Double southLat,
            @RequestParam Double eastLng,
            @RequestParam Double westLng,
            @RequestParam(required = false) String cuisineType,
            @RequestParam(required = false) Integer minPrice,
            @RequestParam(required = false) Integer maxPrice,
            @RequestParam(required = false) Double minRating) {
        
        // 获取指定区域内的餐厅
        List<Restaurant> restaurants = restaurantService.getRestaurantsInArea(
                northLat, southLat, eastLng, westLng, cuisineType, minPrice, maxPrice, minRating);
        
        // 转换为地图标记格式
        List<Map<String, Object>> markers = convertToMarkers(restaurants);
        
        return Result.success(markers);
    }
    
    /**
     * 获取餐厅详情（用于地图信息窗口）
     */
    @GetMapping("/restaurant/{id}")
    public Result<Map<String, Object>> getRestaurantForMap(@PathVariable Long id) {
        Result<Restaurant> restaurantResult = restaurantService.getRestaurantDetail(id);
        
        if (restaurantResult.getCode() != 200) {
            return Result.error(restaurantResult.getMsg());
        }
        
        Restaurant restaurant = restaurantResult.getData();
        
        // 获取餐厅评论数量和平均评分
        int reviewCount = restaurantService.getRestaurantReviewCount(id);
        double avgRating = restaurant.getRating() != null ? restaurant.getRating() : 0.0;
        
        // 获取静态地图URL
        String location = restaurant.getLongitude() + "," + restaurant.getLatitude();
        String staticMapUrl = getStaticMapUrl(location);
        
        Map<String, Object> result = new HashMap<>();
        result.put("id", restaurant.getId());
        result.put("name", restaurant.getName());
        result.put("address", restaurant.getAddress());
        result.put("image", restaurant.getImage());
        result.put("cuisineType", restaurant.getCuisineType());
        result.put("rating", avgRating);
        result.put("priceLevel", restaurant.getPriceLevel());
        result.put("description", restaurant.getDescription());
        result.put("latitude", restaurant.getLatitude());
        result.put("longitude", restaurant.getLongitude());
        result.put("reviewCount", reviewCount);
        result.put("staticMapUrl", staticMapUrl);
        
        return Result.success(result);
    }
    
    /**
     * 获取静态地图URL
     */
    private String getStaticMapUrl(String location) {
        String url = String.format("%s/staticmap?key=%s&location=%s&zoom=14&size=600*300&markers=mid,0xFF0000,A:%s&scale=2",
                AMAP_REST_BASE_URL,
                amapConfig.getRestKey(),
                location,
                location);
        return url;
    }
    
    /**
     * 将餐厅列表转换为地图标记格式
     */
    private List<Map<String, Object>> convertToMarkers(List<Restaurant> restaurants) {
        List<Map<String, Object>> markers = new java.util.ArrayList<>();
        
        for (Restaurant restaurant : restaurants) {
            // 只处理有经纬度的餐厅
            if (restaurant.getLatitude() != null && restaurant.getLongitude() != null 
                && !restaurant.getLatitude().isEmpty() && !restaurant.getLongitude().isEmpty()) {
                try {
                    // 尝试解析经纬度，确保是有效的数值
                    Double lat = Double.parseDouble(restaurant.getLatitude());
                    Double lng = Double.parseDouble(restaurant.getLongitude());
                    
                    Map<String, Object> marker = new HashMap<>();
                    marker.put("id", restaurant.getId());
                    marker.put("name", restaurant.getName());
                    marker.put("latitude", lat);
                    marker.put("longitude", lng);
                    marker.put("cuisineType", restaurant.getCuisineType());
                    marker.put("rating", restaurant.getRating());
                    marker.put("priceLevel", restaurant.getPriceLevel());
                    
                    markers.add(marker);
                } catch (NumberFormatException e) {
                    // 忽略无效的经纬度
                    System.out.println("无效的经纬度: " + restaurant.getName() + ", lat=" + restaurant.getLatitude() + ", lng=" + restaurant.getLongitude());
                }
            }
        }
        
        return markers;
    }
} 